package com.qhnu.zxjx.interceptor;

import com.qhnu.zxjx.context.AppContext;
import com.qhnu.zxjx.context.UserContext;
import com.qhnu.zxjx.enums.SystemCodeEnum;
import com.qhnu.zxjx.exception.CustomException;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 用户拦截器
 * @author: panpei
 * @date: 2019/11/13 13:38
 * @version: 1.0
 **/
@Component
public class UserInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = LogManager.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.info("UserInterceptor preHandle, url:{}", request.getRequestURL().toString());
		String userId = request.getHeader("userId");
		if (StringUtils.isBlank(userId)) {
			userId = request.getParameter("userId");
		}
		String token = request.getHeader("token");
		if (StringUtils.isBlank(token)) {
			token = request.getParameter("token");
		}
		if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(token)) {
			UserContext context = new UserContext();
			context.setUserId(userId);
			context.setToken(token);
			AppContext.USER_CONTEXT.set(context);
		} else {
			throw new CustomException(SystemCodeEnum.ERROR_AUTHORIZED);
		}

		return true;
	}
}
